<?php

namespace App\Console\Commands\PuiblicRds\PublicFs;

use App\Models\Kms\User\KmsUser;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SyncFsUserInfoCommand extends Command
{
    protected $signature = 'publicRds:publicFs:SyncFsUserInfo';

    protected $description = '同步飞书用户信息到公开库中';

    public function handle()
    {
        // 只在线上数据库中执行
        if (!isProd()) {
            return;
        }

        // 清空所有数据
        DB::connection('mysqlPublicFsRds')->table('fs_user')->truncate();

        // 获取所有用户信息
        $userAll = KmsUser::query()
                          ->select([
                              'nickname',
                              'name',
//                              'departmentName',
                              'groupParentDepartment',
                              'jobTitle',
                              'isExited',
                              'joinTime'
                          ])
                          ->where('nickname', '!=', '')
//                          ->limit(1)
                          ->get()
                          ->unique('nickname')
                          ->each(function ($item) {
                              $exportDepartment  = explode('/', $item->groupParentDepartment);
                              $item->createdAt   = time();
                              $item->updatedAt   = time();
                              $item->nickname    = trim($item->nickname);
                              $item->joinTime    = date('Y-m-d', $item->joinTime);
                              $item->department1 = $exportDepartment[0] ?? '';
                              $item->department2 = $exportDepartment[1] ?? '';
                              $item->department3 = $exportDepartment[2] ?? '';

                              unset($item->groupParentDepartment);
                          })
                          ->toArray();

        DB::connection('mysqlPublicFsRds')->table('fs_user')->insert($userAll);
    }

}
